<?php

namespace App\Console\Commands\Clickhouse;

use App\Models\Clickhouse\Guanyuan\GyDmDaySalesAnalyseCHModel;
use App\Remote\Guanyuan\GuanyuanRetry\GuanyuanRetryRemote;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;

class SysGyDmDaySalesAnalyseCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'clickhouse:sys:gyDmDaySalesAnalyse {isFullDose?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步 观远订货数据 -> clickhouse';

    public int $id = 0;

    public array $fields = [
        "newAndOldJudgment",
        "date",
        "commodityCode",
        "unitPriceIncludingTaxCost",
        "salesUnitPriceIncludingTax",
        "vendorCode",
        "warehouseName",
        "salesAmount",
        "profit",
        "cost",
        "tradeName",
        "orderQuantity",
        "orderGoodsQuantity",
        "uniformName",
        "commodityClassification",
        "perfectCoding",
        "supplierAbbreviation",
        "provinceWhereTheStoreIsLocated",
        "cityWhereTheStoreIsLocated",
        "theDistrictWhereTheStoreIsLocated",
        "orderingHouse",
        "storeStatusOriginal",
        "storesWithOrdersInTheLast30Days",
        "numberOfOrders",
        "sort",
        "refund_num",
        "canRefundPrice",
        "productCategory",
        "primaryClassification",
        "timeOfPayment",
        "orderAmount",
        "storeStatus",
        "region",
        "whetherToUnifyOrNot",
        "code",
        "createdAt",
        "updatedAt"
    ];

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     */
    public function handle(): int
    {
        $isFullDose = (bool)$this->input->getArgument("isFullDose");

        try {
            ini_set('memory_limit', '2G');
            $last = GyDmDaySalesAnalyseCHModel::query()->orderByDesc("id")->first();

            if ($isFullDose) {
                // todo 全量跑数据
                if ($last) {
                    $this->id    = $last->id;
                    $executeDate = $last->timeOfPayment;
                    GyDmDaySalesAnalyseCHModel::query()->where("timeOfPayment", ">=", $last->timeOfPayment)->delete();
                } else {
                    $this->id    = 0;
                    $executeDate = "2021-01-30";
                }
            } else {
                // todo 增量数据脚本执行
                if ($last) {
                    $this->id    = $last->id;
                    $executeDate = Carbon::createFromDate($last->timeOfPayment)->subDays(7)->format("Y-m-d");
                    GyDmDaySalesAnalyseCHModel::query()->where("timeOfPayment", ">=", $executeDate)->delete();
                } else {
                    $this->id    = 0;
                    $executeDate = "2021-01-30";
                }
            }


            $execute = true;
            $nowDate = Carbon::now()->format("Y-m-d");
            while ($execute && $executeDate <= $nowDate) {
                $this->getOutput()->info(
                    "$executeDate 正在执行...  [内存占用:  " . (memory_get_usage(true) / 1024 / 1024) . "MB ]"
                );

                $batchInsert = [];
                $response    = GuanyuanRetryRemote::sourceData(
                    'v27df9aef074c43baaf4547e',
                    'j17188a2660f94e93b68f0d0',
                    [
                        [
                            'name'        => '支付时间',
                            'filterType'  => 'EQ',
                            'filterValue' => [$executeDate]
                        ]
                    ]
                );

                if (empty($response["data"]) && $nowDate != $executeDate) {
                    //执行脚本日期 == 拉取观远数据日期 数据为空此时为异常状态
                    $this->getOutput()->warning("{$executeDate} 当天数据为空");
//                    throw new \Exception("观远拉取数据异常 [ $executeDate ]");
                }

                $this->getOutput()->info("当天 {$executeDate} 数据量 :  " . count($response["data"] ?? []));
                if ($response["data"]) {
                    collect($response["data"])->each(function ($row) use (
                        &$batchInsert
                    ) {
                        $this->id = $this->id + 1;
                        $insert   = [
                            "id"        => $this->id,
                            "createdAt" => time()
                        ];
                        collect($row)->each(function ($value, $key) use (&$insert, &$batchInsert) {
                            if (isset($this->fields[$key])) {
                                if ($this->fields[$key] == "orderingHouse") {
                                    $insert["storeCode"] = (int)ltrim(substr($value, 0, 4), 0);
                                }
                                $insert[$this->fields[$key]] = $value;
                            } else {
                                return false;
                            }
                        });

                        array_push($batchInsert, $insert);
                    });

                    collect($batchInsert)->chunk(500)->each(function (Collection $collection) {
                        GyDmDaySalesAnalyseCHModel::query()->insert($collection->values()->toArray());
                    });
                }

                unset($response);
                $executeDate = date("Y-m-d", strtotime(" +1 day", strtotime($executeDate)));
            }

            logInfo("{$this->description} 成功", collect([]), true, false);

        } catch (\Exception $exception) {
            var_dump($exception->getMessage());die;
            logException("{$this->description} 失败", $exception, null, true, true);
        }

        return 0;
    }
}
